package com.marry.mybatis.redis.config;

import com.marry.mybatis.redis.util.ApplicationContextHolder;
import org.apache.ibatis.cache.Cache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class RedisCache implements Cache {
    private static final Logger logger= LoggerFactory.getLogger(RedisCache.class);

    private static final long EXPIRE_TIME_IN_MINUTES = 30; // redis过期时间
    private RedisTemplate redisTemplate;

    private final ReadWriteLock readWriteLock=new ReentrantReadWriteLock();

    private final String id;

    public RedisCache(String id){
        if (id==null){
            throw new IllegalArgumentException("Cache instance require an ID");
        }

        this.id=id;

    }
    @Override
    public String getId() {
        return id;
    }

    @Override
    public void putObject(Object key, Object value) {

        RedisTemplate redisTemplate=getRedisTemplate();
        ValueOperations valueOperations=redisTemplate.opsForValue();
        valueOperations.set(key,value,EXPIRE_TIME_IN_MINUTES, TimeUnit.MINUTES);
        logger.info("Put query result to redis");


    }

    private RedisTemplate getRedisTemplate() {
        if(redisTemplate==null){
            redisTemplate= (RedisTemplate) ApplicationContextHolder.getBean("redisTemplate");
        }
        return redisTemplate;
    }

    @Override
    public Object getObject(Object key) {
        RedisTemplate redisTemplate=getRedisTemplate();
        ValueOperations opsForValue=redisTemplate.opsForValue();
        logger.info("Get cached query result for redis");
        return opsForValue.get(key);
    }

    @Override
    public Object removeObject(Object key) {
        RedisTemplate redisTemplate=getRedisTemplate();
        redisTemplate.delete(key);
        logger.info("Remove cached query result from redis");
        return null;
    }

    @Override
    public void clear() {
        RedisTemplate redisTemplate=getRedisTemplate();
        redisTemplate.execute(new RedisCallback() {
            @Override
            public Object doInRedis(RedisConnection redisConnection) throws DataAccessException {
                redisConnection.flushDb();
                return null;
            }
        });
        logger.info("clear all the cached query result from redis");

    }

    @Override
    public int getSize() {
        return 0;
    }

    @Override
    public ReadWriteLock getReadWriteLock() {
        return readWriteLock;
    }
}
